//
//  HttpRequest.m
//  TuYangTu
//
//  Created by Jpwang on 16/10/9.
//  Copyright © 2016年 Jpwang. All rights reserved.
//




#import "HttpRequest.h"

#define TID           @"tid"
#define TIMESTAMP_KEY @"timestamp"
#define NONCE_KEY     @"nonce"
#define sign          @"sign"

@interface HttpRequest ()

@end

@implementation HttpRequest

+ (HttpRequest *)shareInstance {
    static HttpRequest *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[HttpRequest alloc] init];
        //[NSHTTPCookieStorage sharedHTTPCookieStorage].cookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways;
        //_sharedInstance.responseSerializer = [AFJSONResponseSerializer serializer];
        //_sharedInstance.requestSerializer =  [AFJSONRequestSerializer serializer];
        _sharedInstance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];
        _sharedInstance.requestSerializer.timeoutInterval = 40;
        
    });
    return _sharedInstance;
}

// 网络请求返回后预先处理一遍
- (void)prepareHander:(id)object {
    [super prepareHander:object];
    @try {
        if ([object[@"code"] intValue] == 4036) {
            [[UserManager shareInstance] logout];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"relogin" object:object];
        }
    } @catch (NSException *exception) {
        
    }
}

- (void)handleResult:(id<RACSubscriber>)subscriber responseObject:(id)responseObject operation:(AFHTTPRequestOperation *)operation url:(NSString *)url {
    [super handleResult:subscriber responseObject:responseObject operation:operation url:url];
//    4036
    
}

#pragma mark API接入
- (RACSignal *)regSms:(NSDictionary *)dic {
    NSMutableDictionary *param = [self handleData:dic];
    NSString *url = [NSString stringWithFormat:@"%@%@", baseUrl, URL_user_reg_sms];
    return [self post:url parms:param];
}

- (RACSignal *)reg:(NSDictionary *)dic chipher:(NSData *)chipher {
    NSMutableDictionary *param = [self handleData:dic chipher:chipher];
    NSString *url = [NSString stringWithFormat:@"%@%@", baseUrl, URL_user_reg];
    return [self post:url parms:param];
}

- (RACSignal *)login:(NSDictionary *)dic chipher:(NSData *)chipher {
    NSMutableDictionary *param = [self handleData:dic chipher:chipher];
    NSString *url = [NSString stringWithFormat:@"%@%@", baseUrl, URL_user_login];
    return [self post:url parms:param];
}

- (RACSignal *)updatePwdSms:(NSDictionary *)dic {
    NSMutableDictionary *param = [self handleData:dic];
    NSString *url = [NSString stringWithFormat:@"%@%@", baseUrl, URL_update_pwd_sms];
    return [self post:url parms:param];
}

- (RACSignal *)updatePwd:(NSDictionary *)dic chipher:(NSData *)chipher {
    NSMutableDictionary *param = [self handleData:dic chipher:chipher];
    NSString *url = [NSString stringWithFormat:@"%@%@", baseUrl, URL_update_pwd];
    return [self post:url parms:param];
}


- (RACSignal *)signGet:(NSString *)url map:(NSMutableDictionary *)dic {
    NSMutableDictionary *data = Sign(dic);
    if (data) {
        return [self get:url parms:data];
    } else {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            NSDictionary *result = @{@"code":@"100001", @"message":@"用户信息错误"};
            [subscriber sendNext:result];
            return nil;
        }];
    }
}

- (RACSignal *)signPost:(NSString *)url map:(NSMutableDictionary *)dic {
    NSMutableDictionary *data = Sign(dic);
    if (data) {
        return [self post:url parms:data];
    } else {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            NSDictionary *result = @{@"code":@"100001", @"message":@"用户信息错误"};
            [subscriber sendNext:result];
            return nil;
        }];
    }
}

#pragma mark 登录数据加密
// 数据加密
- (NSMutableDictionary *)handleData:(NSDictionary *)dic {
    // 生成128位AES密钥
    NSData *data = [JPAES random128BitAESKey];
    return [self handleData:dic chipher:data];
}

// 数据加密
- (NSMutableDictionary *)handleData:(NSDictionary *)dic chipher:(NSData *)data{
    // 需要加密的数据转换成字符串
    NSString *str = dicToJSONString(dic);
    // 加密数据
    NSString *encryptData = [JPAES AES128EncryptWithPlainText:str pwdData:data];
    // 加密密钥
    NSData *temp = [RSAUtil encryptData:data publicKey:public_key];
    // 加密的密钥转换成字符串
    NSString *encryptKey = [[NSString alloc] initWithData:[temp base64EncodedDataWithOptions:0] encoding:NSUTF8StringEncoding];
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setObject:encryptData forKey:@"encryptData"];
    [param setObject:encryptKey forKey:@"encryptKey"];
    return param;
}

#pragma mark 加密算法

NSMutableDictionary *Sign(NSMutableDictionary *dic) {
    if ([[UserManager shareInstance] isUserLogin]) {
        User *user = [UserManager shareInstance].user;
        dic = dic==nil ? [[NSMutableDictionary alloc] init] : dic;
        return buildSign(user.tid, user.token, dic);
    } else {
        return nil;
    }
}

NSMutableDictionary *buildSign(NSString *tid, NSString *appSecret, NSMutableDictionary *dic) {
    long time = [currentTimeMillis() longLongValue]/1000;
    NSInteger data =  arc4random()/10000;
    
    [dic setObject:tid forKey:TID];
    [dic setObject:intToString(time) forKey:TIMESTAMP_KEY];
    [dic setObject:[JpMD5Util getmd5WithString:(intToString(data))] forKey:NONCE_KEY];
    [dic setObject:buildParams(dic, appSecret) forKey:sign];
    return dic;
}

NSString *buildParams(NSMutableDictionary *dic, NSString* secret) {
    NSString *content = @"";
    NSMutableArray *keyArray = [NSMutableArray arrayWithArray:dic.allKeys];
    [keyArray sortUsingComparator: ^NSComparisonResult (NSString *str1, NSString *str2) {
        return [str1 compare:str2];
    }];
    for (NSString *key in keyArray) {
        NSString *value = [dic objectForKey:key];
        if (value) {
            content = [NSString stringWithFormat:@"%@%@%@", content, key, value];
        }
    }
    return buildSecret(content, secret);
}

NSString *buildSecret(NSString *content, NSString* secret) {
    NSString *signContent = [NSString stringWithFormat:@"%@%@%@", secret, content, secret];
    return hash(signContent);
}

NSString *hash(NSString *content) {
    return  [JpMD5Util getmd5WithString:content];
}

@end

